﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Caliburn.Micro;
using System.Collections.Generic;
using DomusDotNet.Sbm.Client.WP7.Services;
using DomusDotNet.Sbm.Client.WP7.Framework;
using Microsoft.Phone.Tasks;

namespace DomusDotNet.Sbm.Client.WP7.ViewModels
{
	public class BookListViewModel : Screen, IHasBusyState, IHandle<TaskCompleted<PhoneNumberResult>>
	{

		IPhoneService phone;
		INavigationService navigation;
		IEventAggregator events;
		System.Action pendingSetup;
		public BookListViewModel(IPhoneService phone, INavigationService navigation, IEventAggregator events)
		{
			this.phone = phone;
			this.navigation = navigation;
			this.events = events;
			events.Subscribe(this);

			this.Books = new BindableCollection<BookViewModel>();
			this.BusyState = new BusyState();
		}

		public BindableCollection<BookViewModel> Books { get; private set; }


		public void Setup<TResult>(string title, IQuery<TResult> query) where TResult : IEnumerable<BookViewModel>
		{
			this.DisplayName = title;
			pendingSetup = () => Coroutine.BeginExecute(InitializeFromQueryInternal(query).GetEnumerator());
		}

		protected override void OnActivate()
		{
			if (pendingSetup != null)
			{
				pendingSetup();
				pendingSetup = null;
			}
		}


		public void Share(BookViewModel book)
		{

			events.RequestTask<EmailComposeTask>(x =>
			{
				x.Subject = "Have a look at this book!";
				x.Body = book.Title;
			});
		}

		public void ChooseNumber()
		{

			events.RequestTask<PhoneNumberChooserTask>(state: DisplayName);
		}

		void IHandle<TaskCompleted<PhoneNumberResult>>.Handle(TaskCompleted<PhoneNumberResult> message)
		{
			if (DisplayName.Equals(message.State))
				MessageBox.Show("Remember to call " + message.Result.PhoneNumber);
		}


		IEnumerable<IResult> InitializeFromQueryInternal<TResult>(IQuery<TResult> query) where TResult : IEnumerable<BookViewModel>
		{
			using (BusyState.Set("loading books..."))
			{
				var result = query.AsResult();
				yield return result;

				this.Books.Clear();
				this.Books.AddRange(result.Response);
			}
		}

		public BusyState BusyState { get; private set; }




















		public void GoToDetail(BookViewModel item)
		{
			if (item == null) return;

			var uri = "/Views/Book/Detail.xaml";
			phone.State["book.detail"] = item;
			navigation.Navigate(new Uri(uri, UriKind.Relative));
		}


	}
}
